<?php
/**
 *
 * @package
 * @version 1.0.0 
 * @author Olivier ROGER <roger.olivier@gmail.com>
 * @copyright  2007-2009 Prynel
 *       
 *
 */
if(!empty($_POST['login']) && !empty($_POST['password']) && $_GET['log'] == 'in')
{
	$auth->login($_POST['login'],$_POST['password']);
	try{
		$writer 	= new Log_Writer_File(ROOT_PATH.'logs/connexions/');
		$writer->setDuration(Log_Writer_File::MONTHLY);
		$logs 		= new Log_Log($writer);
	}
	catch(Util_ExceptionHandler $e){
		echo $e->getMessage();
	}
	
	if(!$auth->error)
	{
		$prepared 	= $sql->prepare('SELECT id,login,nom,prenom,email FROM users WHERE login=:login');
		$prepared->execute(array(':login'=>$_POST['login']));
		$user 		= $prepared->fetchObject();
		
		$session->id 		= $user->id;
		$session->login		= $user->login;
		$session->nom		= $user->nom;
		$session->prenom	= $user->prenom;
		$session->email		= $user->email;
		
		$ACL = new Auth_ACL();
		if(isset($session->id))
		{
			$ressources = $sql->query('SELECT nom FROM droits');
			while($ressource = $ressources->fetch(PDO::FETCH_ASSOC))
				$ACL->addRessource($ressource['nom'],0);
				
			$prepared = $sql->prepare('SELECT d.nom 
										FROM droits_users du 
										LEFT JOIN droits d ON d.id = du.idDroit 
										WHERE du.idUser=:user');
			$prepared->execute(array(':user'=>$session->id));
			while($exception = $prepared->fetch(PDO::FETCH_ASSOC))
				$ACL->allowUser($exception['nom'],true);
			
			$session->acl = serialize($ACL);
			$prepared = $sql->prepare('UPDATE users SET last_co=:time WHERE id=:id');
			$prepared->execute(array(':time'=>time(),':id'=>$session->id));
		}
		
		$logs->info('Connexion de '.$user->login);
		header('Location: /calendrier/view.html');
	}
	else
	{
		$logs->warn('Erreur de connexion pour '.$_POST['login']);
		echo $auth->getErrorType();
		header('Location: index.php?mod=login&act=login&el='.$auth->getErrorType());
	}
}
else
{
	$auth->logout();
	$template = $twig->loadTemplate('login/identification.html');
	echo $template->render($view);
}
 ?>